package cn.bocweb.spinning.view.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.UpdateInfoBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.ContainsEmojiEditText;
import cn.bocweb.spinning.view.common.GlideCircle;
import de.greenrobot.event.EventBus;

public class MyInfoActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.my_info_icon)
    ImageView myInfoIcon;
    @Bind(R.id.btn_save)
    TextView btnSave;
    @Bind(R.id.my_info_main)
    LinearLayout myInfoMain;
    @Bind(R.id.my_info_nickname)
    EditText myInfoNickname;
    @Bind(R.id.btn_my_info_gender)
    RelativeLayout btnMyInfoGender;
    @Bind(R.id.my_info_realname)
    ContainsEmojiEditText myInfoRealname;
    @Bind(R.id.my_info_company)
    ContainsEmojiEditText myInfoCompany;
    @Bind(R.id.my_info_duty)
    ContainsEmojiEditText myInfoDuty;
    @Bind(R.id.my_info_phone)
    ContainsEmojiEditText myInfoPhone;
    @Bind(R.id.my_info_addr)
    ContainsEmojiEditText myInfoAddr;
    @Bind(R.id.my_info_code)
    ContainsEmojiEditText myInfoCode;

    String nickName;
    String realName;
    String companyName;
    String dutyName;
    String phoneNum;
    String addrName;
    String codeNum;

    LinearLayout btn_male, btn_female;
    String capturePath, path, base, userid;
    PopupWindow pop;
    int gender = 1;
    UserPresenter presenter;
    @Bind(R.id.my_info_mobile)
    TextView myInfoMobile;
    @Bind(R.id.my_info_mobile_btn)
    LinearLayout myInfoMobileBtn;
    RelativeLayout window_gender_layout;

    InputMethodManager inputMethodManager;
    Uri uri;
    View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_person);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        presenter = new UserPresenterImp();
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        initToolbar();
        initPopupWindow();
        initClickBtn();
        initInfo();
        nickNameListener();
        realNameListener();
        companyNameListener();
        dutyNameListener();
        telNumListener();
        addrNameListener();
        codeNumListener();
        myInfoMain.setFocusable(true);
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private void initInfo() {
        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);
        userid = user.getUserid();
        String icon = user.getUthumb();
        if (icon == null || icon.isEmpty()) {
            myInfoIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
        } else {
            Glide.with(this).load(icon).transform(new GlideCircle(this)).into(myInfoIcon);
        }
        if (user.getGender().equals("1")) {
            ((TextView)btnMyInfoGender.getChildAt(1)).setText("男");
            gender = 1;
        } else if (user.getGender().equals("2")) {
            ((TextView)btnMyInfoGender.getChildAt(1)).setText("女");
            gender = 2;
        } else {
            ((TextView)btnMyInfoGender.getChildAt(1)).setText("空");
        }

        myInfoNickname.setText(user.getNickname());
        nickName = user.getNickname();

        myInfoRealname.setText(user.getRealname());
        realName = user.getRealname();
        myInfoCompany.setText(user.getCompany());
        companyName = user.getCompany();
        myInfoDuty.setText(user.getPosition());
        dutyName = user.getPosition();
        myInfoPhone.setText(user.getTel());
        phoneNum = user.getTel();
        myInfoAddr.setText(user.getAddress());
        addrName = user.getAddress();
        myInfoCode.setText(user.getCode());
        codeNum = user.getCode();
        myInfoMobile.setText(user.getPhone());
    }

    private void nickNameListener() {

        myInfoNickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    nickName = s.toString();
                }
                if (s.toString().length() > 6) {
                    DeviceUtil.MyToast(MyInfoActivity.this, "昵称最多6个字");
                }
            }
        });

        myInfoNickname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    myInfoNickname.setText("");
                } else {
                    myInfoNickname.setText(nickName);
                }
            }
        });
    }

    private void realNameListener() {
        myInfoRealname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    realName = s.toString();
                }
                if (s.toString().length() > 8) {
                    DeviceUtil.MyToast(MyInfoActivity.this, "真实姓名最多8个字");
                }
            }
        });

        myInfoRealname.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    myInfoRealname.setText("");
                } else {
                    myInfoRealname.setText(realName);
                }
            }
        });
    }

    private void companyNameListener() {
        myInfoCompany.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    companyName = s.toString();
                }
                if (s.toString().length() > 19) {
                    DeviceUtil.MyToast(MyInfoActivity.this, "公司名称最多19个字");
                }
            }
        });

        myInfoCompany.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    myInfoCompany.setText("");
                } else {
                    myInfoCompany.setText(companyName);
                }
            }
        });
    }

    private void dutyNameListener() {
        myInfoDuty.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    dutyName = s.toString();
                }
                if (s.toString().length() > 15) {
                    DeviceUtil.MyToast(MyInfoActivity.this, "职位最多15个字");
                }
            }
        });

        myInfoDuty.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    myInfoDuty.setText("");
                } else {
                    myInfoDuty.setText(dutyName);
                }
            }
        });
    }

    private void telNumListener() {
        myInfoPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    phoneNum = s.toString();
                }
                if (s.toString().length() > 13) {
                    DeviceUtil.MyToast(MyInfoActivity.this, "电话最多13个字");
                }
            }
        });

        myInfoPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    myInfoPhone.setText("");
                } else {
                    myInfoPhone.setText(phoneNum);
                }
            }
        });
    }

    private void addrNameListener() {
        myInfoAddr.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    addrName = s.toString();
                }
                if (s.toString().length() > 50) {
                    DeviceUtil.MyToast(MyInfoActivity.this, "地址最多19个字");
                }
            }
        });

        myInfoAddr.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    myInfoAddr.setText("");
                } else {
                    myInfoAddr.setText(addrName);
                }
            }
        });
    }

    private void codeNumListener() {
        myInfoCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    codeNum = s.toString();
                }
                if (s.toString().length() > 6) {
                    DeviceUtil.MyToast(MyInfoActivity.this, "邮编最多6个字");
                }
            }
        });

        myInfoCode.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    myInfoCode.setText("");
                } else {
                    myInfoCode.setText(codeNum);
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initPopupWindow() {
        view = LayoutInflater.from(this).inflate(R.layout.window_gender, null);
        btn_male = (LinearLayout) view.findViewById(R.id.btn_gender_male);
        btn_female = (LinearLayout) view.findViewById(R.id.btn_gender_female);
        window_gender_layout = (RelativeLayout) view.findViewById(R.id.window_gender_layout);
        pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        pop.setAnimationStyle(R.style.popup_window);

    }

    private void initClickBtn() {
        myInfoIcon.setOnClickListener(this);
        btn_male.setOnClickListener(this);
        btn_female.setOnClickListener(this);
        btnSave.setOnClickListener(this);
        btnMyInfoGender.setOnClickListener(this);
        myInfoMobileBtn.setOnClickListener(this);
        window_gender_layout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_info_mobile_btn: {
                DeviceUtil.MyToast(this, "手机号无法更改");
                break;
            }
            case R.id.my_info_icon:
                myInfoIcon();
                break;
            case R.id.btn_my_info_gender: {
                pop.showAtLocation(myInfoMain, Gravity.BOTTOM, 0, 0);
                if (inputMethodManager.isActive()) {
                    inputMethodManager.hideSoftInputFromWindow(myInfoMain.getApplicationWindowToken(), 0);
                }
                break;
            }
            case R.id.btn_gender_male:
                pop.dismiss();
                gender = 1;
                ((TextView)btnMyInfoGender.getChildAt(1)).setText("男");
                break;
            case R.id.btn_gender_female:
                pop.dismiss();
                gender = 2;
                ((TextView)btnMyInfoGender.getChildAt(1)).setText("女");
                break;
            case R.id.btn_save: {
                if (inputMethodManager.isActive()) {
                    inputMethodManager.hideSoftInputFromWindow(myInfoMain.getApplicationWindowToken(), 0);
                }
                submitMyInfoSava();
                break;
            }
            case R.id.window_gender_layout: {
                pop.dismiss();
                break;
            }
        }
    }

    private void submitMyInfoSava() {
        try {
            String nickname = myInfoNickname.getText().toString();
            String realname = myInfoRealname.getText().toString();
            String company = myInfoCompany.getText().toString();
            String position = myInfoDuty.getText().toString();
            String tel = myInfoPhone.getText().toString();
            String address = myInfoAddr.getText().toString();
            String code = myInfoCode.getText().toString();

            String filename = System.currentTimeMillis() + "icon.jpg";

            File file;
            if (path != null) {
                file = new File(path);
            } else {
                file = null;
            }

            if (DeviceUtil.isCode(code)) {
                showLoading();
                presenter.updateInfo(userid, nickname, realname, company, position, tel, String.valueOf(gender), address, code, file, filename);
            } else {
                DeviceUtil.MyToast(this, "请输入正确的邮编");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    public void onEventMainThread(UpdateInfoBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {
            UserBean.DataEntity user = new UserBean.DataEntity();
            user.readInfoFromLocal(this);
            if (bean.getData().getUthumb() != null && !bean.getData().getUthumb().isEmpty()) {
                user.setUthumb(bean.getData().getUthumb());
                Glide.with(this).load(bean.getData().getUthumb()).transform(new GlideCircle(this)).into(myInfoIcon);
            } else {
                myInfoIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
            }

            if (bean.getData().getNickname() != null && !bean.getData().getNickname().isEmpty()) {
                user.setNickname(bean.getData().getNickname());
                myInfoNickname.setText(bean.getData().getNickname());
            }
            if (bean.getData().getGender() != null && !bean.getData().getGender().isEmpty()) {
                user.setGender(bean.getData().getGender());
                if (Integer.parseInt(bean.getData().getGender()) == 1) {
                    ((TextView)btnMyInfoGender.getChildAt(1)).setText("男");
                } else {
                    ((TextView)btnMyInfoGender.getChildAt(1)).setText("女");
                }
            }
            if (bean.getData().getRealname() != null && !bean.getData().getRealname().isEmpty()) {
                user.setRealname(bean.getData().getRealname());
                myInfoRealname.setText(bean.getData().getRealname());
            }
            if (bean.getData().getCompany() != null && !bean.getData().getCompany().isEmpty()) {
                user.setCompany(bean.getData().getCompany());
                myInfoCompany.setText(bean.getData().getCompany());
            }
            if (bean.getData().getPosition() != null && !bean.getData().getPosition().isEmpty()) {
                user.setPosition(bean.getData().getPosition());

                myInfoDuty.setText(bean.getData().getPosition());
            }

            if (!TextUtils.isEmpty(bean.getData().getTel())) {
                user.setTel(bean.getData().getTel());
                myInfoPhone.setText(bean.getData().getTel());
            }

            if (bean.getData().getPhone() != null && !bean.getData().getPhone().isEmpty()) {
                user.setPhone(bean.getData().getPhone());
                myInfoMobile.setText(bean.getData().getPhone());
            }
            if (bean.getData().getAddress() != null && !bean.getData().getAddress().isEmpty()) {
                user.setAddress(bean.getData().getAddress());
                myInfoAddr.setText(bean.getData().getAddress());
            }
            if (bean.getData().getCode() != null && !bean.getData().getCode().isEmpty()) {
                user.setCode(bean.getData().getCode());
                myInfoCode.setText(bean.getData().getCode());
            }
            user.writeInfoIntoLocal(this);
            finish();
        } else {
            DeviceUtil.Log(bean.getMsg());
        }
    }


    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }

    private void myInfoIcon() {
        if (Build.VERSION.SDK_INT >= 23) {
            int camarePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            int photoPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (camarePermission != PackageManager.PERMISSION_GRANTED || photoPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                        this,
                        new String[]{
                                Manifest.permission.CAMERA,
                                Manifest.permission.READ_EXTERNAL_STORAGE}, 301);
                return;
            }
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setItems(new String[]{"拍照", "从相册中选择"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        chooseCamera();
                        break;
                    case 1:
                        chooseAlbum(dialog);
                        break;
                }
            }
        });
        builder.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 301: {
                if (grantResults[0]== PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("提示");
                    builder.setItems(new String[]{"拍照", "从相册中选择"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case 0:
                                    chooseCamera();
                                    break;
                                case 1:
                                    chooseAlbum(dialog);
                                    break;
                            }
                        }
                    });
                    builder.show();
                } else {
                    DeviceUtil.MyToast(MyInfoActivity.this, "获取相关权限失败");
                }
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void myInfoEditDialog(final TextView tv, int state) {
        View view = LayoutInflater.from(this).inflate(R.layout.view_edit, null);
        final EditText editText = (EditText) view.findViewById(R.id.dialog_edit);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setView(view);

        builder.setPositiveButton("提交", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv.setText(editText.getText().toString());
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.CHOOSE_ALBUM: {
                try {
                    uri = data.getData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                getAlbum(uri);
                break;
            }
            case Constant.CHOOSE_CAMERA: {
                getCamera();
                break;
            }
        }

    }

    private void getAlbum(Uri uri) {
        try {
            if (uri != null) {
                path = DeviceUtil.getImageAbsolutePath(this, uri);
                Glide.with(this).load(path).transform(new GlideCircle(this)).into(myInfoIcon);
                base = DeviceUtil.encodeBase64File(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getCamera() {
        try {
            if (capturePath != null) {
                path = capturePath;
                DeviceUtil.Log("path = " + path);
                Glide.with(this).load(path).transform(new GlideCircle(this)).into(myInfoIcon);
                base = DeviceUtil.encodeBase64File(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initToolbar() {
        toolbar.setTitle("修改资料");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(Constant.LOGIN_TO_MAIN);
                finish();
            }
        });
    }


    private void chooseAlbum(DialogInterface dialog) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, Constant.CHOOSE_ALBUM);
        dialog.dismiss();
    }

    private void chooseCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            capturePath = Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + ".jpg";
            DeviceUtil.Log("capturePath = " + capturePath);
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(capturePath)));
            getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(getImageByCamera, Constant.CHOOSE_CAMERA);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }
}
